package com.waverider.promotion.biz.manager.impl;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.taobao.api.ApiException;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.ArticleUserSubscribe;
import com.taobao.api.domain.Shop;
import com.taobao.api.domain.User;
import com.taobao.api.request.IncrementCustomerPermitRequest;
import com.taobao.api.request.ShopGetRequest;
import com.taobao.api.request.UserGetRequest;
import com.taobao.api.request.VasSubscribeGetRequest;
import com.taobao.api.response.IncrementCustomerPermitResponse;
import com.taobao.api.response.ShopGetResponse;
import com.taobao.api.response.UserGetResponse;
import com.taobao.api.response.VasSubscribeGetResponse;
import com.waverider.promotion.biz.dao.ShopDAO;
import com.waverider.promotion.biz.manager.ShopManager;
import com.waverider.promotion.constants.PromotionConstants;
import com.waverider.promotion.domain.ShopDO;

public class ShopManagerImpl implements ShopManager {
	private static final Log logger = LogFactory.getLog(ShopManagerImpl.class);

	private ShopDAO shopDAO;
	private TaobaoClient taobaoClient;

	@Override
	public void add(ShopDO shop) {
		shopDAO.insert(shop);
	}

	@Override
	public void addOrUpdate(ShopDO shop) {
		ShopDO originalShop = getBySellerId(shop.getSellerId());

		if (originalShop == null) {
			add(shop);
		} else {
			shop.setId(originalShop.getId());
			update(shop);
		}
	}

	@Override
	public boolean update(ShopDO shop) {
		return shopDAO.update(shop);
	}

	@Override
	public ShopDO getBySellerId(Long sellerId) {
		return shopDAO.queryBySellerId(sellerId);
	}

	@Override
	public ShopDO getByShopId(Long shopId) {
		return shopDAO.queryByShopId(shopId);
	}

	@Override
	public boolean delete(Long id) {
		return shopDAO.delete(id);
	}

	@Override
	public ShopDO syncShopInfoFromTaobao(String topSessionKey, Long vistorId,
			String vistorNick) {
		ShopDO shop = new ShopDO();
		shop.setSellerId(vistorId);
		shop.setSellerNick(vistorNick);
		shop.setIsDeleted(false);

		try {
			// 先取店铺基本信息
			ShopGetRequest shopRequest = new ShopGetRequest();
			shopRequest
					.setFields("sid,cid,title,nick,desc,bulletin,pic_path,created,modified");
			shopRequest.setNick(vistorNick);

			ShopGetResponse shopResponse = taobaoClient.execute(shopRequest);
			Shop tbShop = shopResponse.getShop();
			shop.setShopId(tbShop.getSid());
			shop.setShopName(tbShop.getTitle());

			// 先取商家信息
			UserGetRequest userRequest = new UserGetRequest();
			userRequest
					.setFields("user_id,nick,seller_credit,location,birthday,type,alipay_account,alipay_no,email");
			UserGetResponse userResponse = taobaoClient.execute(userRequest,
					topSessionKey);
			User user = userResponse.getUser();
			shop.setAlipayAccount(user.getAlipayAccount());
			shop.setAlipayNo(user.getAlipayNo());
			shop.setSessionKey(topSessionKey);

			// 开通消息通知
			if (!openMessageService(topSessionKey)) {
				throw new RuntimeException(new StringBuilder("为商家:")
						.append(vistorNick).append(" 开通主动通知业务失败！！！").toString());
			}
		} catch (ApiException e) {
			logger.error(e);
			throw new RuntimeException(e);
		}

		addOrUpdate(shop);

		return shop;
	}

	private boolean openMessageService(String topSessionKey)
			throws ApiException {
		IncrementCustomerPermitRequest request = new IncrementCustomerPermitRequest();
		IncrementCustomerPermitResponse response = taobaoClient.execute(
				request, topSessionKey);

		return response.isSuccess();
	}

	public void setShopDAO(ShopDAO shopDAO) {
		this.shopDAO = shopDAO;
	}

	public void setTaobaoClient(TaobaoClient taobaoClient) {
		this.taobaoClient = taobaoClient;
	}

	@Override
	public boolean isUnfree(String nick) {

		VasSubscribeGetRequest req = new VasSubscribeGetRequest();
		req.setNick(nick);
		req.setArticleCode(PromotionConstants.SERVICE_CODE_VERSION);
		try {
			VasSubscribeGetResponse response = taobaoClient.execute(req);
			if (response.getArticleUserSubscribes() != null) {
				for (ArticleUserSubscribe subscribe : response
						.getArticleUserSubscribes()) {
					if (PromotionConstants.SERVICE_CODE_VERSION_UNFREE
							.equals(subscribe.getItemCode())
							&& new Date().before(subscribe.getDeadline()))
						return true;
				}
			}
		} catch (ApiException e) {
			logger.error(e);
			throw new RuntimeException(e);
		}
		return false;
	}
}
